<?php
/**
 * Created by b17
 * 2/15/12 6:46 PM
 */

namespace Managers\Email;

require_once APPLICATION_PATH . '/data/Managers/Utils/PHPExcel.php';

class Excel extends Source
{
    /**
     * @var \PHPExcel_Reader_IReader[]
     */
    protected $readers = array();

    protected function init()
    {
        $this->addReader(new \PHPExcel_Reader_Excel2003XML());
        $this->addReader(new \PHPExcel_Reader_Excel2007());
        $this->addReader(new \PHPExcel_Reader_Excel5());
    }

    public function addReader(\PHPExcel_Reader_IReader $reader)
    {
        $this->readers[] = $reader;
    }

    protected function parse($file)
    {
        $reader = $this->getReader($file);
        $excel = $reader->load($file);
        /* @var \PHPExcel $excel */
        $cells = $excel->getActiveSheet()->getCellCollection();
        $result = array();
        foreach ($cells as $cell) {
            $result[] = $excel->getActiveSheet()->getCell($cell)->getValue();
        }
        return $result;
    }

    /**
     * @param $file
     * @return \PHPExcel_Reader_IReader
     * @throws \LogicException
     */
    private function getReader($file)
    {
        foreach ($this->readers as $reader) {
            if ($reader->canRead($file)) {
                return $reader;
            }
        }
        throw new \LogicException('Unsupported file format.');
    }
}
